import Vue from 'vue'
import KshComponent from './ksh.vue'
import * as rego from '../../utils/rego' // 暂时未使用，先注释掉

// 创建弹窗构造函数 - renamed to start with capital letter
const MwkshConstructor = Vue.extend(KshComponent)
window.MwkshConstructor = MwkshConstructor

// 创建弹窗组件实例的方法
function createInstance() {
  const instance = new MwkshConstructor({
    el: document.createElement('div')
  })
  document.body.appendChild(instance.$el)
  return instance
}

// 注册全局弹窗方法
window.$modalMwksh = {
  show(options = {}) {
    const instance = createInstance()
    // 合并配置项
    Object.assign(instance.$data, options)
    // 设置标题
    if (options.title) {
      instance.modalTitle = options.title
    }
    // 设置回调函数
    if (options.onClose) {
      instance.onClose = options.onClose
    }
    if (options.onConfirm) {
      instance.onConfirm = options.onConfirm
    }
    if (options.onSelect) {
      instance.onSelect = options.onSelect
    }
    if (options.filterConfig) {
      instance.filterConfig = options.filterConfig
    }
    if (options.callbackConfig) {
      instance.callbackConfig = options.callbackConfig
    }
    // 设置是否多选
    if (typeof options.multiple === 'boolean') {
      instance.multiple = options.multiple
    }
    instance.visible = true
    window.modalMwkshInstance = instance
    return instance
  },

  hide() {
    if (window.modalMwkshInstance) {
      // 调用关闭回调
      if (typeof window.modalMwkshInstance.onClose === 'function') {
        window.modalMwkshInstance.onClose()
      }
      window.modalMwkshInstance.visible = false
      // 延迟移除DOM
      setTimeout(() => {
        if (window.modalMwkshInstance && window.modalMwkshInstance.$el && window.modalMwkshInstance.$el.parentNode) {
          document.body.removeChild(window.modalMwkshInstance.$el)
          window.modalMwkshInstance.$destroy()
          window.modalMwkshInstance = null
        }
      }, 300)
    }
  }
}






// 注册为Vue插件
export default {
  install(Vue) {
    Vue.prototype.$modalMwksh = window.$modalMwksh
  }
}